from fastapi import APIRouter, Form, Depends, HTTPException, status
from fastapi.responses import JSONResponse
from fastapi.security import OAuth2PasswordBearer
from jose import JWTError, jwt
from config import SECRET_KEY, ALGORITHM, ADMIN_CREDENTIALS
from crud.user import Info_Base, Oldpwd_Check, Info_Get, Login, Update_Message, Pwd_Update, Register
from routers.models import User_Login, User_Pwd_Update, UserInfo, RegisterRequest

router = APIRouter(tags=["用户基础服务"])


# OAuth2 认证
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")

@router.get("/")
async def hello():
    return {"msg": "hello"}


@router.post("/loginService")
async def loginService(user: User_Login):
    print("当前用户ID为：", user.uUserName)
    token_data = await Login.selectUserByName(user.uUserName, user.uPassword)
    print("查询结果为：", token_data)

    if not token_data:
        print("无此用户")
        return JSONResponse(content={"success": False, "message": "用户名或密码错误"})

    return JSONResponse(content={"success": True, "token": token_data["access_token"], "token_type": token_data["token_type"], "is_admin": token_data["is_admin"]})

@router.post("/registerService")
async def registerService(request: RegisterRequest):
    id = request.id
    password = request.password
    name = request.name
    gender = request.gender
    age = request.age
    weight = request.weight
    height = request.height

    print("注册用户ID为：", id)
    if id in ADMIN_CREDENTIALS:
        return JSONResponse(content={"success": False, "message": "注册错误"})
    success = await Register.insertUserInfo(id, password)
    print("插入结果为：", success)
    if not success:
        return JSONResponse(content={"success": False, "message": "注册错误"})

    if (not await Info_Base.insertUserInfo(id, name, gender, age, height, weight)):
        return JSONResponse(content={"success": False, "message": "插入失败"})

    return JSONResponse(content={"success": True, "message": "成功"}) 


# 依赖函数：验证 Token 并获取用户 ID
async def get_current_user_id(token: str = Depends(oauth2_scheme)):
    credentials_exception = HTTPException(
        status_code=status.HTTP_401_UNAUTHORIZED,
        detail="Could not validate credentials",
        headers={"WWW-Authenticate": "Bearer"},
    )
    try:
        payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
        user_id: str = payload.get("sub")
        if user_id is None:
            raise credentials_exception
        return user_id
    except JWTError:
        raise credentials_exception


@router.post("/changePassword")
async def changePassword(passWord: User_Pwd_Update,
    user_id: str = Depends(get_current_user_id)):
    oldPassword = passWord.oldPassword
    newPassword = passWord.newPassword
    print(user_id, oldPassword, newPassword)
    data1 = await Oldpwd_Check.oldPwd_check(user_id)

    if not data1:
        return JSONResponse(content={"oldpwdCheck": False, "oldnewCheck": False, "changeSucceed": False})

    s1 = data1[0]
    print(s1)

    for key, value in s1.items():
        if value != oldPassword:
            return JSONResponse(content={"oldpwdCheck": False, "oldnewCheck": False, "changeSucceed": False})

    await Pwd_Update.newPwd_update(user_id, newPassword)
    print("密码修改成功")
    return JSONResponse(content={"oldpwdCheck": True, "oldnewCheck": True, "changeSucceed": True})


@router.post("/getMessage")
async def getMessage(user_id: str = Depends(get_current_user_id)):
    data = await Info_Get.getpersonalMessage(user_id)
    if data is None:
        raise HTTPException(status_code=404, detail="User not found")
    return JSONResponse(content={"data": data})


@router.post("/updateMessage")
async def updateMessage(
        Info: UserInfo,
        ID: str = Depends(get_current_user_id)):
    print("用户信息：", ID, Info.name, Info.gender, Info.age, Info.height, Info.weight)
    if (not await Update_Message.update_message(ID, Info.name, Info.gender, Info.age, Info.weight, Info.height)):
        return JSONResponse(content={"updateSucceed": False})
    return JSONResponse(content={"updateSucceed": True})
